package com.hitqz.robot.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.RobotMap;
import com.hitqz.robot.api.dispatch.protocol.dto.RobotMapDto;
import com.hitqz.robot.biz.mapper.RobotMapMapper;
import com.hitqz.robot.biz.service.RobotConfigService;
import com.hitqz.robot.biz.service.RobotMapService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.netty.service.Send2ServerService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xupkun
 * @date 2024/5/21
 */
@Service
@AllArgsConstructor
@Slf4j
public class RobotMapServiceImpl extends ServiceImpl<RobotMapMapper, RobotMap> implements RobotMapService {

    private final RobotService robotService;

    private Send2ServerService send2ServerService;

    private final RobotConfigService robotConfigService;

    private final ServerProperties serverProperties;

    @Override
    public RobotMap findByMapCode(String mapCode) {
        return baseMapper.findByMapCode(mapCode);
    }

    @Override
    public void syncMap() {
        List<RobotMap> robotMaps = baseMapper.selectList(null);
        Robot robot = robotService.getDefaultRobot();
        if (CollectionUtil.isNotEmpty(robotMaps)) {
            for (RobotMap robotMap : robotMaps) {
                RobotMapDto robotMapDto = new RobotMapDto();
                BeanUtil.copyProperties(robotMap, robotMapDto, false);
                robotMapDto.setClientId(robot.getRobotSn());
                if (StrUtil.isNotBlank(robotMap.getFilePath())){
                    try {
                        robotMapDto.setDownloadUrl(robotConfigService.getOneEnable().getProcessManagerUri() + robotMap.getFilePath());
                    }catch (Exception e){
                        log.error("sync map get downLoadUrl error",e);
                    }
                }
                send2ServerService.syncRobotMapInfo(0, robotMapDto);
            }
        }
    }
}
